const { ajax } = require("../../utils/index");

Page({
  data: {
    name: '',
    phone: '',
    house_number: '',
    datetimeVisible: false,
    buildingPickerVisible: false,
    repairPickerVisible: false,
    datetime: new Date().getTime(),
    datetimeText: '',
    building_number: '',//楼栋号key
    repair_type: '',// 故障类型key
    buildingnumber_label: '',//楼栋号标题
    repairtype_label: '',// 故障类型标题
    buildingNumberList: [],  // 楼栋号数据列表
    repairList: [],          // 故障类型数据列表
    fault_desc: '',
    fileList: [],
    repair_img :''
  },

  getName(e) {
    this.setData({
      name: e.detail.value
    });
  },

  getPhone(e) {
    this.setData({
      phone: e.detail.value
    });
  },

  onBuildingPicker() {
    this.setData({
      buildingPickerVisible: true
    });
  },

  onBuildingPickerChange(e) {
    console.log('onBuildingPickerChange:', e.detail);
    this.setData({
      buildingnumber_label: e.detail.label[0],
      building_number: e.detail.value[0],
      buildingPickerVisible: false
    });
  },

  onBuildingPickerCancel() {
    this.setData({
      buildingPickerVisible: false
    });
  },

  getHouseNumber(e) {
    this.setData({
      house_number: e.detail.value
    });
  },

  showPicker() {
    this.setData({
      datetimeVisible: true
    });
  },

  hidePicker() {
    this.setData({
      datetimeVisible: false
    });
  },

  onConfirm(e) {
    const { value } = e.detail;
    this.setData({
      datetimeText: value,
      datetimeVisible: false
    });
  },

  onFaultPicker() {
    this.setData({
      repairPickerVisible: true
    });
  },

  onRepairPickerChange(e) {
    console.log('onRepairPickerChange', e.detail);
    this.setData({
      repairtype_label: e.detail.label[0],
      repair_type: e.detail.value[0],
      repairPickerVisible: false
    });
  },

  onPickerCancel() {
    this.setData({
      repairPickerVisible: false
    });
  },

  getFaultDesc(e) {
    this.setData({
      fault_desc: e.detail.value
    });
  },

  handleAddImg(e) {
  // console.log('ee',e.detail.files[0].url);
  // console.log( e.detail.files[0]);
  wx.uploadFile({
    url: 'http://localhost:8080/common/upload',
    filePath: e.detail.files[0].url, 
    name: 'file',
    success: (res) => {
      try {
        const data = JSON.parse(res.data);
        if (data.code === 200) {
          // console.log(data.fileName);
          this.data.repair_img = data.fileName
          // console.log(this.data.repair_img);
          const newUrls = data.url.split(',');
          // console.log('newUrls',this.data.fileList);
          this.setData({
            fileList: [...this.data.fileList,{ url: newUrls[0] }]
          });
        }
      } catch (error) {
        console.error('Failed to parse response:', error);
      }
    },
    fail: (err) => {
      console.log('Upload failed:', err);
    }
  });
  },

  handleRemove(e) {
    const { fileList } = this.data;
    const { index } = e.detail;
    fileList.splice(index, 1);
    this.setData({
      fileList: fileList
    });
  },

  async submit() {
    const { name, phone, building_number, house_number, datetimeText, repair_type, repair_img, fault_desc } = this.data;
    const wxLogin = wx.getStorageSync('wxLogin');//登录状态
    const userInfo = wx.getStorageSync('userInfo');//微信用户信息
    const loginInfo = wx.getStorageSync('loginInfo');//登录用户信息
    
    console.log('wxLogin',wxLogin);
    console.log('userInfo',userInfo);
    console.log('loginInfo',loginInfo);
    const params = {
      user_id: loginInfo.userId,
      openid: userInfo.openid,
      user_info: userInfo.nickName,
      name,
      phone,
      building_number,
      house_number,
      visit_time: datetimeText,
      repair_type,
      repair_img,
      fault_desc,
    };

    console.log('params',params);
    const { data } = await ajax('/api/repair-orders/add', 'POST', params);
    if(data.code===200){
      wx.navigateBack({
        success:()=>{
          wx.showToast({
            title: '提交成功！',
          })
        }
      })
    }else{
      wx.showToast({
        title: '提交失败！请重试！',
      })
    }
  },

  onLoad() {
    this.fetchBuildingNumbers();
    this.fetchRepairTypes();
    
  },

  async fetchBuildingNumbers() {
    try {
      const response = await ajax('/api/dict-data/building-number', 'GET');
      // console.log('res',response);
      if (response.data.code === 200) {
        const { data } = response.data
        this.setData({
          buildingNumberList: data.map(item => ({
            label: item.dictLabel,
            value: item.dictValue
          }))
        });
      } else {
        console.error('Failed to fetch building numbers:', response.msg);
      }
    } catch (error) {
      console.error('Error fetching building numbers:', error);
    }
  },

  async fetchRepairTypes() {
    try {
      const response = await ajax('/api/dict-data/repair-type', 'GET');
      if (response.data.code === 200) {
        const { data } = response.data
        this.setData({
          repairList: data.map(item => ({
            label: item.dictLabel,
            value: item.dictValue
          }))
        });
      } else {
        console.error('Failed to fetch repair types:', response.msg);
      }
    } catch (error) {
      console.error('Error fetching repair types:', error);
    }
  },

  onReady() { },

  onShow() { },

  onHide() { },

  onUnload() { },

  onPullDownRefresh() { },

  onReachBottom() { },

  onShareAppMessage() { }
});